package pers.lmy.stockTrading.service;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import pers.lmy.stockTrading.dao.BalanceMapper;
import pers.lmy.stockTrading.dao.OrderMapper;
import pers.lmy.stockTrading.dao.PositionMapper;
import pers.lmy.stockTrading.entity.Order;
import pers.lmy.stockTrading.entity.Position;

import java.math.BigDecimal;
import java.util.List;

@Service
public class TradeService {
    @Autowired
    private BalanceMapper balanceMapper;
    @Autowired
    private PositionMapper positionMapper;
    @Autowired
    private OrderMapper orderMapper;

    public List<Order> getOrderList(int userid) {
        return orderMapper.selectByUserId(userid);
    }

    public void buyStock(int userid, String stockCode, String stockName,
            BigDecimal price, int number) {
        //生成订单
        BigDecimal totalBuyPrice = price.multiply(new BigDecimal(number));
        BigDecimal commission = calculateBuyCommission(totalBuyPrice);
        totalBuyPrice = totalBuyPrice.add(commission);
        orderMapper.insert(userid, stockCode, stockName, price, number,
                           totalBuyPrice, 0);
        //更改余额
        BigDecimal balance =
                balanceMapper.selectByUserId(userid).get(0).getBalance();
        balanceMapper.update(userid, balance.subtract(totalBuyPrice));
        //更改持仓
        List<Position> positionList = positionMapper.selectByUserId(userid);
        boolean insert = true;
        int ownNumber = 0;
        BigDecimal ownCost = new BigDecimal(0);
        for (Position position : positionList) {
            if (position.getStockcode().equals(stockCode)) {
                insert = false;
                ownNumber = position.getNumber();
                ownCost = position.getCost();
                break;
            }
        }
        //账户若已有该股票使用update，若没有则使用add
        if (insert) {
            positionMapper.insert(userid, stockCode, stockName, price, number);
        } else {
            BigDecimal totalPrice = ownCost.multiply(new BigDecimal(ownNumber))
                    .add(totalBuyPrice);
            int totalNumber = ownNumber + number;
            positionMapper.update(userid, stockCode, totalPrice
                    .divide(new BigDecimal(totalNumber), 2,
                            BigDecimal.ROUND_HALF_UP), totalNumber);
        }
    }

    public void sellStock(int userid, String stockCode, String stockName,
            BigDecimal price, int number) {
        //生成订单
        BigDecimal totalSellPrice = price.multiply(new BigDecimal(number));
        BigDecimal commission = calculateSellCommission(totalSellPrice);
        totalSellPrice = totalSellPrice.subtract(commission);
        orderMapper.insert(userid, stockCode, stockName, price, number,
                           totalSellPrice, 1);
        //更改余额
        BigDecimal balance =
                balanceMapper.selectByUserId(userid).get(0).getBalance();
        balanceMapper.update(userid, balance.add(totalSellPrice));
        //更改持仓
        List<Position> positionList = positionMapper.selectByUserId(userid);
        BigDecimal cost = new BigDecimal(0);
        int numberAfterSell = 0;
        for (Position position : positionList) {
            if (position.getStockcode().equals(stockCode)) {
                cost = position.getCost();
                numberAfterSell = position.getNumber() - number;
                break;
            }
        }
        //卖出后该股票数为0使用delete，若不为0使用update
        if (numberAfterSell == 0) {
            positionMapper.delete(userid, stockCode);
        } else {
            positionMapper.update(userid, stockCode, cost, numberAfterSell);
        }
    }

    public BigDecimal calculateBuyCommission(BigDecimal total) {
        BigDecimal commission = total.multiply(new BigDecimal(0.0003));
        if (commission.compareTo(new BigDecimal(5)) == -1) {
            commission = new BigDecimal(5);
        }
        return commission.stripTrailingZeros();
    }

    public BigDecimal calculateSellCommission(BigDecimal total) {
        BigDecimal commission = total.multiply(new BigDecimal(0.0003));
        if (commission.compareTo(new BigDecimal(5)) == -1) {
            commission = new BigDecimal(5);
        }
        BigDecimal transfer = total.multiply(new BigDecimal(0.00002));
        if (transfer.compareTo(new BigDecimal(2)) == -1) {
            transfer = new BigDecimal(2);
        }
        BigDecimal tax = total.multiply(new BigDecimal(0.001));
        commission = commission.add(transfer);
        commission = commission.add(tax);
        return commission.stripTrailingZeros();
    }
}
